const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')

//路由中间件
router.use((req, res, next) => {
    console.log('Time:', Date.now())
    next()
})
router.get('/', (req, res) => {
    res.render('index', { title: 'Hey', message: 'Hello there!' })
})
router.all('/all', (req, res, next) => {
    res.send('所有的请求都会进来')
    console.log(req.method);
    // next() // pass control to the next handler

})
router.get('/all', (req, res) => {
    console.log('get请求all');
})

router.get('/hello', (req, res) => {
    res.send('Hello World')

})
router.get('/getinfo/:id/:name', (req, res) => {
    console.log(req.params);
    console.log(req.query);
    res.send(`你好${req.params.name + req.params.id}`)
})
router.get('/users/:userId/books/:bookId', function (req, res) {
    console.log(req.params);
    res.json(req.params)
})
//上传文件
router.post('/upload', (req, res) => {
    let fileObject = null
    if (!req.files || Object.keys(req.files).length == 0) {
        res.status(400).send({
            message: '上传失败:',
            code: 500
        })
        return
    }
    fileObject = req.files.file
    // filePath = __dirname+'/upload/' + fileObject.file
    const fileFolder = path.join(__dirname, 'upload')

    if (!fs.existsSync(fileFolder)) {
        fs.mkdirSync(fileFolder)
    }
    let filePath = path.join(fileFolder, fileObject.name);
    fileObject.mv(filePath, (err) => { 
        if (err) { 
            console.log(err);
            return res.status(500).send({
                code: 1,
                msg:'System error'
            })
        }
        res.send({
            code: 0,
            data:'Upload Successfully '
        })
    })

})

module.exports = router